package com.gdou.tlias.filter;

import com.alibaba.fastjson.JSONObject;
import com.gdou.tlias.pojo.Result;
import com.gdou.tlias.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.UrlPathHelper;

import java.io.IOException;

@Slf4j
//@WebFilter
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1.获取请求url
        String s = request.getRequestURI();
        log.info("请求的url：{}",s);
        //2.判断请求url是否包含login，如果包含，说明是登录请求，放行
        if(s.contains("login")){
            log.info("登陆操作，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.获取请求头中的令牌
        String jwt=request.getHeader("token");
        //4.判断令牌是否存在，如果不存在，返回错误信息（未登录）
        if(jwt==null|| jwt.isEmpty()){
            log.info("请求头token为空，返回未登录的信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin=JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        //5.解析token，如果解析失败，返回错误结果（未登录）

        try {
            JwtUtils.parseJwt(jwt);
        }catch(Exception e){
            e.printStackTrace();
            log.info("解析失败，返回未登录错误信息");
            Result error=Result.error("NOT_LOGIN");
            String notLogin=JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        //6.放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("放行之后的逻辑");
    }
}
